package app.biz.service.legacy;

import app.framework.exception.ValidateException;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Service;

import java.util.Map;

/** Created by gulx@neusoft.com on 2018/12/12. */
@Service
public class LBServiceSimpleImpl implements LBService {

  LBProxy proxy;

  /** 负载均衡目标对象代理 */
  class LBProxy {
    /** 负载目标 */
    Map<Integer, String> targetMap = Maps.newConcurrentMap();
    /** 当前索引 */
    int cur = 0;
  }

  @Override
  public LBService load(String[] targetUrl) {
    proxy = new LBProxy();
    if (targetUrl.length == 0) {
      throw new ValidateException("负载均衡目标对象不能为空！");
    }
    for (int i = 0; i < targetUrl.length; i++) {
      proxy.targetMap.put(i, targetUrl[i]);
    }
    return this;
  }

  @Override
  public String get() {
    if (proxy.targetMap ==null || proxy.targetMap.size() == 0) {
      throw new ValidateException("负载均衡目标不能为空！");
    }
    if (proxy.cur == proxy.targetMap.size()) {
      proxy.cur = 0;
    }
    return proxy.targetMap.get(proxy.cur++);
  }

//  public static void main(String[] args) {
//    SimpleLBServiceImpl simpleLBService = new SimpleLBServiceImpl();
//    simpleLBService.load(new String[] {"a", "b", "c"});
//    System.out.println(simpleLBService.get());
//    System.out.println(simpleLBService.get());
//    System.out.println(simpleLBService.get());
//    System.out.println(simpleLBService.get());
//    System.out.println(simpleLBService.get());
//    System.out.println(simpleLBService.get());
//  }
}
